package core;

import gitobject.Commit;
import gitobject.Tree;
import repository.Repository;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;

import fileoperation.FileReader;

public class JitLog {
	/**
	 * Add files into your index.
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	public static void log() throws IOException {
		/* Todo: You should pass the filename in this function, and generate a hash file in your repository.
		 *   Add your code here.*/
		String content = "";

		File head = Commit.getNowHeadFile();
		if(head == null) System.out.println("fatal: \"HEAD\" does not exist in the repository: .jit");
		else {
			if (head.exists()) {
				try {
					String commitId = Commit.getLastCommit();
					while(!Objects.equals(commitId, "" ) && commitId != null){
						Commit commit = Commit.deserialize(commitId);
						assert commit != null;
						printCommitInfo(commit);
						commitId = commit.getParent();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				System.out.printf("fatal: branch \"%s\" does not exist", head.getName());
				throw new IOException("Repository is not exist, please check");
			}
		}
	}

	private static void printCommitInfo(Commit commit) {
		String[] info = commit.getAuthor().split("\\s+");
		String time;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy Z", Locale.ENGLISH);
		Date date = new Date(Long.parseLong(info[2]) * 1000);
		time = simpleDateFormat.format(date);
		System.out.println("Commit " + commit.getKey());
		System.out.println("Author:\t" + info[0] + " " + info[1]);
		System.out.println("Date:\t" + time + "\n");
		System.out.println("\t" + commit.getMessage() + "\n");
	}
}